/**
 * 用户认证API接口模块
 * 
 * 核心功能：
 * - 用户登录/注册
 * - 密码管理
 * - 用户信息管理
 * - 权限验证
 * 
 * 最小实现调用方式：
 * import * as authApi from '@/api/auth'
 * const result = await authApi.login({ username, password })
 */

import axios from 'axios'

// 是否使用模拟数据（开发环境默认使用）
const USE_MOCK = import.meta.env.DEV || !import.meta.env.VITE_API_BASE_URL

// 创建axios实例
const api = axios.create({
  baseURL: '/api/auth',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    console.log(`认证API请求: ${config.method?.toUpperCase()} ${config.url}`)
    return config
  },
  (error) => {
    console.error('认证API请求错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    console.log(`认证API响应: ${response.status} ${response.config.url}`)
    return response
  },
  (error) => {
    console.error('认证API响应错误:', error.response?.status, error.message)
    return Promise.reject(error)
  }
)

// 模拟用户数据
const mockUsers = [
  {
    id: '1',
    username: 'admin',
    email: 'admin@mindray.com',
    password: 'admin123', // 实际项目中应该加密存储
    realName: '系统管理员',
    phone: '13800138000',
    role: 'admin',
    status: 'active',
    createdAt: '2024-01-01T00:00:00.000Z'
  },
  {
    id: '2',
    username: 'doctor',
    email: 'doctor@mindray.com',
    password: 'doctor123',
    realName: '医生用户',
    phone: '13800138001',
    role: 'doctor',
    status: 'active',
    createdAt: '2024-01-01T00:00:00.000Z'
  }
]

/**
 * 用户登录
 */
export const login = (loginData) => {
  if (USE_MOCK) {
    console.log('使用模拟数据进行登录:', loginData.username)
    
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        const user = mockUsers.find(u => 
          u.username === loginData.username && u.password === loginData.password
        )
        
        if (user) {
          const token = `mock_token_${user.id}_${Date.now()}`
          const userInfo = {
            id: user.id,
            username: user.username,
            email: user.email,
            realName: user.realName,
            phone: user.phone,
            role: user.role,
            status: user.status
          }
          
          resolve({
            data: {
              token,
              user: userInfo,
              expiresIn: 7200 // 2小时
            }
          })
        } else {
          reject(new Error('用户名或密码错误'))
        }
      }, 800) // 模拟网络延迟
    })
  }
  
  return api.post('/login', loginData)
}

/**
 * 用户注册
 */
export const register = (registerData) => {
  if (USE_MOCK) {
    console.log('使用模拟数据进行注册:', registerData.username)
    
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        // 检查用户名是否已存在
        const existingUser = mockUsers.find(u => 
          u.username === registerData.username || u.email === registerData.email
        )
        
        if (existingUser) {
          reject(new Error('用户名或邮箱已存在'))
          return
        }
        
        // 创建新用户
        const newUser = {
          id: String(Date.now()),
          username: registerData.username,
          email: registerData.email,
          password: registerData.password,
          realName: registerData.realName,
          phone: registerData.phone,
          role: 'user',
          status: 'active',
          createdAt: new Date().toISOString()
        }
        
        mockUsers.push(newUser)
        
        const userInfo = {
          id: newUser.id,
          username: newUser.username,
          email: newUser.email,
          realName: newUser.realName,
          phone: newUser.phone,
          role: newUser.role,
          status: newUser.status
        }
        
        resolve({
          data: {
            user: userInfo,
            message: '注册成功'
          }
        })
      }, 1000) // 模拟网络延迟
    })
  }
  
  return api.post('/register', registerData)
}

/**
 * 用户登出
 */
export const logout = () => {
  if (USE_MOCK) {
    console.log('使用模拟数据进行登出')
    return Promise.resolve({
      data: {
        message: '登出成功'
      }
    })
  }
  
  const token = localStorage.getItem('auth_token')
  return api.post('/logout', {}, {
    headers: {
      'Authorization': `Bearer ${token}`
    }
  })
}

/**
 * 获取当前用户信息
 */
export const getCurrentUser = () => {
  if (USE_MOCK) {
    console.log('使用模拟数据获取当前用户信息')
    const userInfo = localStorage.getItem('user_info')
    if (userInfo) {
      return Promise.resolve({
        data: JSON.parse(userInfo)
      })
    } else {
      return Promise.reject(new Error('用户未登录'))
    }
  }
  
  const token = localStorage.getItem('auth_token')
  return api.get('/me', {
    headers: {
      'Authorization': `Bearer ${token}`
    }
  })
}

/**
 * 修改密码
 */
export const changePassword = (passwordData) => {
  if (USE_MOCK) {
    console.log('使用模拟数据修改密码')
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        const userInfo = JSON.parse(localStorage.getItem('user_info') || '{}')
        const user = mockUsers.find(u => u.id === userInfo.id)
        
        if (user && user.password === passwordData.oldPassword) {
          user.password = passwordData.newPassword
          resolve({
            data: {
              message: '密码修改成功'
            }
          })
        } else {
          reject(new Error('原密码错误'))
        }
      }, 500)
    })
  }
  
  const token = localStorage.getItem('auth_token')
  return api.put('/change-password', passwordData, {
    headers: {
      'Authorization': `Bearer ${token}`
    }
  })
}

/**
 * 重置密码
 */
export const resetPassword = (resetData) => {
  if (USE_MOCK) {
    console.log('使用模拟数据重置密码:', resetData.email)
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        const user = mockUsers.find(u => u.email === resetData.email)
        if (user) {
          resolve({
            data: {
              message: '重置密码邮件已发送'
            }
          })
        } else {
          reject(new Error('邮箱地址不存在'))
        }
      }, 1000)
    })
  }
  
  return api.post('/reset-password', resetData)
}

/**
 * 验证token有效性
 */
export const validateToken = (token) => {
  if (USE_MOCK) {
    console.log('使用模拟数据验证token')
    return Promise.resolve({
      data: {
        valid: token && token.startsWith('mock_token_'),
        user: JSON.parse(localStorage.getItem('user_info') || '{}')
      }
    })
  }
  
  return api.post('/validate-token', { token })
}

/**
 * 刷新token
 */
export const refreshToken = () => {
  if (USE_MOCK) {
    console.log('使用模拟数据刷新token')
    const userInfo = JSON.parse(localStorage.getItem('user_info') || '{}')
    const newToken = `mock_token_${userInfo.id}_${Date.now()}`
    
    return Promise.resolve({
      data: {
        token: newToken,
        expiresIn: 7200
      }
    })
  }
  
  const token = localStorage.getItem('auth_token')
  return api.post('/refresh-token', {}, {
    headers: {
      'Authorization': `Bearer ${token}`
    }
  })
}

/**
 * 工具函数：检查用户是否已登录
 */
export const isLoggedIn = () => {
  const token = localStorage.getItem('auth_token')
  const userInfo = localStorage.getItem('user_info')
  return !!(token && userInfo)
}

/**
 * 工具函数：获取当前用户角色
 */
export const getCurrentUserRole = () => {
  const userInfo = localStorage.getItem('user_info')
  if (userInfo) {
    return JSON.parse(userInfo).role
  }
  return null
}

/**
 * 工具函数：清除登录信息
 */
export const clearAuthData = () => {
  localStorage.removeItem('auth_token')
  localStorage.removeItem('user_info')
}

export default api
